import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/home/model/app_menu_resp.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/home/model/user_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/config/menu_config.dart';
import 'package:tracker/utils/toast_utils.dart';

mixin HomePageMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
  bool hasThing = false;
  bool showLoading = true;
  int userDeviceCount = 0;

  // 菜单列表
  List<AppMenuData> menuListResp = [];
  List<AppMenuData> menuList = [];

  /// 获取登录用户的信息
  Future<void> fetchUserInfo() async {
    await ref.read(userInfoProvider.notifier).fetchUserInfo((UserInfoData userInfoData) {
      final userType = UserTypeEnum.fromValue(userInfoData.type!);
      ref.read(userTypeProvider.notifier).state = userType;
      userDeviceCount = userInfoData.deviceCount!;
    });
  }

  /// 获取菜单列表
  fetchMenuList() async {
    if (!this.mounted) {
      return;
    }
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    // 获取菜单列表
    menuList = MenuConfig.menuList;
    menuListResp = MenuConfig.menuList;
    // 过滤置顶按钮
    menuList = menuList.where((element) => element.isTop == false).toList();
    menuListResp = menuListResp.where((element) => element.isTop == false).toList();
    // 过滤菜单
    menuList = List.from(menuListResp);
    if (deviceInfo.vipService == false) {
      menuList = menuList.where((element) => element.menuCode != 'vip').toList();
    }
    if (deviceInfo.valueAddedService == false) {
      menuList = menuList.where((element) => element.menuCode != 'valueAddedService').toList();
    }
  }

  /// 根据code获取菜单
  AppMenuData? getMenuByCode(String code) {
    return menuListResp.where((element) => element.menuCode == code).firstOrNull;
  }

  /// 显示购买vip弹窗
  showBuyVipDialog() {
    hasShowRechargeDialog = true;
    ToastUtils.showBuyVip(context, () {
      var vipMenu = getMenuByCode('vip');
      if (vipMenu != null) {
        openPageByPath(vipMenu.path ?? '', vipMenu.menuCode ?? '');
      }
    }, cancelCallback: () async {
      // 设备号登录、手机号登录，直接退出到登录页面
      final userType = ref.watch(userTypeProvider);
      if (userType == UserTypeEnum.device || userType == UserTypeEnum.phone) {
        try {
          await post('/app/user/logout');
        } catch (e) {
          XLogger.error('退出登录失败: $e');
        }
        SpUtil.putBool('isLogin', false);
        // 删除用户信息
        ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
        // 删除设备信息
        ref.read(userInfoProvider.notifier).removeUserInfo();
        context.go(RouterManager.login);
      }
    });
  }

  /// 根据页面地址打开页面（新命名，行为不变）
  navigateByPath(String path, String menuCode) async {
    XLogger.error(menuCode);
    if (menuCode == 'sound') {
      await context.push('${RouterManager.recordHistory}?url=${Uri.encodeComponent('sound')}');

      return;
    }

    if (path.startsWith('http')) {
      await context.push('${RouterManager.web}?url=${Uri.encodeComponent(path)}');
    } else {
      await context.push(path);
    }
    if (menuCode == 'vip') {
      // 刷新设备信息，判断是否需要弹出充值提示
      _judgeShowVipDialogAgain();
    }
  }

  // 兼容旧方法名
  openPageByPath(String path, String menuCode) async {
    return navigateByPath(path, menuCode);
  }

  /// 判断是否需要弹出充值提示
  _judgeShowVipDialogAgain() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei != null && deviceInfo.imei!.isNotEmpty && deviceInfo.showRechargeTip == true) {
      showBuyVipDialog();
    }
  }

  /// 设备更新时间
  String getDeviceUpdateTime(DeviceInfoVO deviceInfo) {
    if (deviceInfo.isNineDevice == true) {
      // 当前时间
      var now = DateTime.now();
      return DateUtil.formatDate(now, format: 'yyyy-MM-dd HH:mm');
    } else {
      return deviceInfo.heartbeatTime ?? '无';
    }
  }

  Future<void> checkAndShowValueAddedServiceAd(BuildContext context) async {
    // ToastUtils.showValueAddedServiceAd(
    //   context,
    //   () {
    //     // 跳转到增值服务页面
    //     context.push(RouterManager.valueAddedService);
    //   },
    // );
    // return;
    var lastShownDate = SpUtil.getString('lastShownValueAddedServiceAdDate');
    String today = DateTime.now().toString().split(' ')[0];

    if (lastShownDate != today) {
      // 检查设备的增值服务按钮是否为"是"
      bool showValueAddedServiceButton = await checkValueAddedServiceButton();

      if (showValueAddedServiceButton) {
        ToastUtils.showValueAddedServiceAd(
          context,
          () {
            // 跳转到增值服务页面
            context.push(RouterManager.valueAddedService);
          },
        );
      }

      // 更新最后显示日期
      await SpUtil.putString('lastShownValueAddedServiceAdDate', today);
    }
  }

  Future<bool> checkValueAddedServiceButton() async {
    // 这里需要实现检查设备的增值服务按钮是否为"是"的逻辑
    // 返回true表示应该显示广告,false表示不应该显示
    // 这可能涉及到API调用或者本地数据检查
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    // 判断增值服务按钮是否为"是"，且秒定模式是否过期，轨迹存储是否小于7天
    if (deviceInfo.valueAddedService == true &&
        deviceInfo.isInstantModeExpired() == true &&
        deviceInfo.trackStorageDays! <= 7) {
      return true;
    }
    return false;
  }

  // 在适当的生命周期方法中调用checkAndShowValueAddedServiceAd
  // 例如:
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 延迟3秒后检查是否显示增值服务广告
      Future.delayed(const Duration(seconds: 3), () {
        checkAndShowValueAddedServiceAd(context);
      });
    });
  }
}
